<%@page import="java.util.ArrayList"%>
<%@page import="java.util.List"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@ page import="java.sql.*"%>
<%@ page import="ch01.User"%>
<%@ page import="ch02.ConnectionManager"%>

<%
	request.setCharacterEncoding("UTF-8");
	String pass = request.getParameter("password");
	String name = request.getParameter("userName");
	//根据用户名查找数据库，匹配密码
	Connection con = null;
	PreparedStatement pStatement = null;
	try {
		con = ConnectionManager.getConnection();
		String sql = "select * from userinfo where loginname=? and password=?";
		pStatement = con.prepareStatement(sql);
		pStatement.setString(1, name);
		pStatement.setString(2, pass);

		ResultSet rs = pStatement.executeQuery();

		if (rs.next()) {
			//			response.sendRedirect("index.jsp");
			//实现访问控制
			User loginUser = new User(name, pass);
			session.setAttribute("LOGIN USER", loginUser);

			List loginedUsers = new ArrayList();
			if (application.getAttribute("LOGINED USER") != null) {

				loginedUsers = (ArrayList) application
						.getAttribute("LOGINED USER");
			}
			boolean flag = true;
			for (int i = 0; i < loginedUsers.size(); i++) {
				User user = (User) loginedUsers.get(i);
				if (user.getName().equals(name)) {
					flag = false;
					break;
				}
			}
			if (flag) {
				loginedUsers.add(loginUser);
			}
			application.setAttribute("LOGINED USER", loginedUsers);

			if (application.getAttribute("COUNT") == null) {
				application.setAttribute("COUNT", 0 + "");
			}
			String num = (String) application.getAttribute("COUNT");
			int n = Integer.parseInt(num);
			n++;
			num = n + "";
			application.setAttribute("COUNT", num);
			response.sendRedirect("index.jsp");
			rs.close();
		} else {
			response.sendRedirect("login.html");
		}

	} catch (Exception e) {
		out.print("发生错误！错误原因：" + e.getMessage());
	} finally {
		ConnectionManager.closeStatement(pStatement);
		ConnectionManager.closeConnection(con);
	}
%>

<%
	//实现访问控制
	//User loginUser = new User(name, pass);
	//session.setAttribute("LOGIN USER", loginUser);
%>

